using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Project.Domain.AggregatesModel;
using Project.Domain.Exceptions;

namespace Project.API.Application.Commands
{
    /// <summary>
    /// 项目查看事件处理
    /// </summary>
    public class ViewProjectCommandHandler:IRequestHandler<ViewProjectCommand>
    {
        private readonly IProjectRepository _projectRepository;
        public ViewProjectCommandHandler(IProjectRepository projectRepository)
        {
            _projectRepository = projectRepository;
        }
        
        public async Task<Unit> Handle(ViewProjectCommand request, CancellationToken cancellationToken)
        {
            var project = await  _projectRepository.GetAsync(request.ProjectId);

            if(project == null) 
                throw new ProjectDomainException($"项目不存在: {request.ProjectId}");


            if(project.UserId == request.UserId) 
                throw new ProjectDomainException($"不能查看自己的项目");
           
            project.AddViewer(request.UserId, request.UserName, request.Avatar);

            await _projectRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
            
            return await Task.FromResult(new Unit());
        }
    }
}